// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import 'isomorphic-fetch';
import * as vscode from 'vscode';
import { AzureDevOpsAuthenticationProvider } from './authProvider';

// 这个方法会在扩展被激活时调用  
// 扩展在第一次执行命令时会被激活 
export function activate(context: vscode.ExtensionContext) {

	console.log('Congratulations, your extension "vscode-authenticationprovider-sample" is now active!');

	// 注册我们的认证提供者。注意：这将全局注册提供者，这意味着  
    // 任何其他扩展都可以通过`getSession` API使用这个提供者。
	context.subscriptions.push(vscode.authentication.registerAuthenticationProvider(
		AzureDevOpsAuthenticationProvider.id,
		'Azure Repos',
		new AzureDevOpsAuthenticationProvider(context.secrets),
	));
	// 注册一个VS Code命令，命令ID为'vscode-authenticationprovider-sample.login'  
	let disposable = vscode.commands.registerCommand('vscode-authenticationprovider-sample.login', async () => {
		// 获取我们的PAT会话  
		const session = await vscode.authentication.getSession(AzureDevOpsAuthenticationProvider.id, [], { createIfNone: true });

		try {
			// 向Azure DevOps API发起请求。请注意，这个特定的API只适用于具有  
            // '所有组织'访问权限的PAT。 
			const req = await fetch('https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=6.0', {
				headers: {
					 // 使用Basic认证方式，并将PAT作为密码进行Base64编码 
					authorization: `Basic ${Buffer.from(`:${session.accessToken}`).toString('base64')}`,
					// eslint-disable-next-line @typescript-eslint/naming-convention
					'content-type': 'application/json',
				},
			});
			if (!req.ok) {
				throw new Error(req.statusText);
			}
			const res = await req.json() as { displayName: string };
			vscode.window.showInformationMessage(`Hello ${res.displayName}`);
		} catch (e: any) {
			if (e.message === 'Unauthorized') {
				// 显示错误消息，提示用户使用具有'所有组织'访问权限的PAT，并建议用户注销后重试  
				vscode.window.showErrorMessage('Failed to get profile. You need to use a PAT that has access to all organizations. Please sign out and try again.');
			}
			throw e;
		}
	});

	context.subscriptions.push(disposable);
}
